package com.wenwei.sharebox.net;




import com.orhanobut.logger.Logger;
import com.wenwei.sharebox.base.BaseApplication;
import com.wenwei.sharebox.base.Constant;
import com.wenwei.sharebox.bean.ApiResultBean;
import com.wenwei.sharebox.bean.AppMsgBean;
import com.wenwei.sharebox.bean.AppointmentBean;
import com.wenwei.sharebox.bean.BannerBean;
import com.wenwei.sharebox.bean.BaseGoodsBean;
import com.wenwei.sharebox.bean.DeviceGoodsBean;
import com.wenwei.sharebox.bean.GoodCateBean;
import com.wenwei.sharebox.bean.GoodsDetailsBean;
import com.wenwei.sharebox.bean.GoodsInfoBean;
import com.wenwei.sharebox.bean.HomeHotGoodsBean;
import com.wenwei.sharebox.bean.MessageListBean;
import com.wenwei.sharebox.bean.OrderGoodsBean;
import com.wenwei.sharebox.bean.ProposalBean;
import com.wenwei.sharebox.bean.RechargeInterageBean;
import com.wenwei.sharebox.bean.RefundBean;
import com.wenwei.sharebox.bean.RegisterBean;
import com.wenwei.sharebox.bean.RentBean;
import com.wenwei.sharebox.bean.ShareGoodsBean;
import com.wenwei.sharebox.bean.SupplyGoodsBean;
import com.wenwei.sharebox.bean.UpdateUserInfoBean;
import com.wenwei.sharebox.bean.UserIdentityBean;
import com.wenwei.sharebox.bean.UserLoginBean;
import com.wenwei.sharebox.bean.UserShareBean;
import com.wenwei.sharebox.bean.WeChatPayConfigBean;
import com.wenwei.sharebox.utils.UserStringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.functions.Func1;

/**
 *
 *
  * 对Retrofit 请求过程进行封装
 */
public class ApiManager {
    public static final int DEFAULT_TIMEOUT = 10;//设置默认超时时间
    private Retrofit retrofit ;
    private ApiInterface mApiService;
    /**
     * 构造方法私有
     */
    private ApiManager(){
        //手动创建一个OkHttpClient并设置超时时间
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
        httpClientBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        httpClientBuilder.addNetworkInterceptor(new LogInterceptor());
        final String s = UserStringUtils.getUserToken(BaseApplication.getAppContext());
        Logger.d("headerToken:"+s);
        httpClientBuilder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request()
                        .newBuilder()
                        .addHeader("Authorization", UserStringUtils.getUserToken(BaseApplication.getAppContext()))
                        .build();
                return chain.proceed(request);
            }
        });
        //Retrofit的一些配置
        retrofit = new Retrofit.Builder()
                .client(httpClientBuilder.build())//配置okHttp
                .addConverterFactory(GsonConverterFactory.create())//配置CallModel可以使用Gson直接创建Bean
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//配置ApiService请求可以使用RxJava
                .baseUrl(Constant.BASE_URL)//配置服务器地址
                .build();//创建

        mApiService = retrofit.create(ApiInterface.class);//创建API请求接口
    }

    private static class SingletonHolder{
        private static final ApiManager INSTANCE = new ApiManager();
    }

    public static ApiManager getInstance(){
        return SingletonHolder.INSTANCE;
    }


    private class HttpResultFunc<T> implements Func1<ApiResultBean<T>, T> {
        @Override
        public T call(ApiResultBean<T> httpResult) {
            if (httpResult.getCode()!=200) {
                throw new ApiException(httpResult.getMessage());
            }
            return httpResult.getData();
        }
    }

    private class BaseGoodsBeanFunc implements Func1<BaseGoodsBean, BaseGoodsBean> {
        @Override
        public BaseGoodsBean call(BaseGoodsBean httpResult) {
            if (httpResult.getCode()!=200) {
                throw new ApiException(httpResult.getMessage());
            }
            return httpResult;
        }
    }


    //注册
    public void userRegister(BaseSubscriber subscriber,String phone,String pw){
        mApiService.userRegister(phone,pw).map(new HttpResultFunc<RegisterBean>())
                .compose(TransformUtils.<RegisterBean>defaultSchedulers())
                .subscribe(subscriber);
    }
    //登录
    public void userLogin(BaseSubscriber subscriber,String userName,String password,String regId){
        mApiService.userLogin(userName,password,regId,"android").map(new HttpResultFunc<UserLoginBean>())
                .compose(TransformUtils.<UserLoginBean>defaultSchedulers())
                .subscribe(subscriber);
    }


    /********************* buy模块 ****************************/
    //创建订单（租用或购买）type 0 表示租用 ， 1 表示购买
    public void createOrder(BaseSubscriber subscriber,int shopId,int type){
        mApiService.createOrder(shopId,type)
                .map(new HttpResultFunc<OrderGoodsBean>())
                .compose(TransformUtils.<OrderGoodsBean>defaultSchedulers())
                .subscribe(subscriber);
    }

    /********************* 开锁模块 ****************************/
    //扫描解锁，或者是输入编号解锁,返回商品详情
    public void deviceUniqueNum(BaseSubscriber subscriber,String bodyJs){
        mApiService.deviceUniqueNum(bodyJs)
                .map(new HttpResultFunc<GoodsInfoBean>())
                .compose(TransformUtils.<GoodsInfoBean>defaultSchedulers())
                .subscribe(subscriber);
    }


    /********************* 支付模块 ****************************/

    public void wxPayConfig(BaseSubscriber subscriber,String orderNum){
        mApiService.wxPayConfig(orderNum)
                .map(new HttpResultFunc<WeChatPayConfigBean>())
                .compose(TransformUtils.<WeChatPayConfigBean>defaultSchedulers())
                .subscribe(subscriber);
    }

    /********************* Profile模块 ****************************/

    public void insetIntegralRecharge(BaseSubscriber subscriber,int userId,float money){
        mApiService.insetIntegralRecharge(userId,money)
                .map(new HttpResultFunc<RechargeInterageBean>())
                .compose(TransformUtils.<RechargeInterageBean>defaultSchedulers())
                .subscribe(subscriber);
    }

    public void getMessageList(BaseSubscriber subscriber){
        mApiService.getMessageList(1,100)
                .map(new HttpResultFunc<ArrayList<MessageListBean>>())
                .compose(TransformUtils.<ArrayList<MessageListBean>>defaultSchedulers())
                .subscribe(subscriber);
    }

    public void applyDeposit(BaseSubscriber subscriber){
        mApiService.applyDeposit()
                .map(new HttpResultFunc<UserIdentityBean>())
                .compose(TransformUtils.<UserIdentityBean>defaultSchedulers())
                .subscribe(subscriber);
    }
    //实名认证
    public void userIdentity(BaseSubscriber subscriber,String idCard,String realName,int userId){
        try{
            mApiService.userIdentity(userId,idCard,realName)
                    .map(new HttpResultFunc<UserIdentityBean>())
                    .compose(TransformUtils.<UserIdentityBean>defaultSchedulers())
                    .subscribe(subscriber);
        }catch (Exception e){
            Logger.d(e.toString());
        }

    }
    //预约
    public void userAppointment(BaseSubscriber subscriber,String bodyJs){
        mApiService.userAppointment(getBody(bodyJs))
                .map(new HttpResultFunc<AppointmentBean>())
                .compose(TransformUtils.<AppointmentBean>defaultSchedulers())
                .subscribe(subscriber);
    }
    //获取用户资料
    public void getUserInfo(BaseSubscriber subscriber){
        mApiService.getUserInfo()
                .map(new HttpResultFunc<UserLoginBean>())
                .compose(TransformUtils.<UserLoginBean>defaultSchedulers())
                .subscribe(subscriber);
    }
    //修改资料
    public void updateUserInfo(BaseSubscriber subscriber,String bodyJs,int userId){
        mApiService.updateUserInfo(getBody(bodyJs),userId).map(new HttpResultFunc<UpdateUserInfoBean>())
                .compose(TransformUtils.<UpdateUserInfoBean>defaultSchedulers())
                .subscribe(subscriber);
    }
    //赚取积分-物品共享
    public void shareGoods(BaseSubscriber subscriber,String bodyJs){
        mApiService.shareGoods(getBody(bodyJs))
                .map(new HttpResultFunc<ShareGoodsBean>())
                .compose(TransformUtils.<ShareGoodsBean>defaultSchedulers())
                .subscribe(subscriber);
    }
    //赚取积分-建议
    public void proposal(BaseSubscriber subscriber,String bodyJs){
        mApiService.proposal(getBody(bodyJs))
                .map(new HttpResultFunc<ProposalBean>())
                .compose(TransformUtils.<ProposalBean>defaultSchedulers())
                .subscribe(subscriber);
    }
    //获取app信息
    public void getAppConfig(BaseSubscriber sb){
        mApiService.getAppConfig()
                .map(new HttpResultFunc<AppMsgBean>())
                .compose(TransformUtils.<AppMsgBean>defaultSchedulers())
                .subscribe(sb);
    }




    /********************* Home模块 ****************************/
    //banner
    public void getBanner(BaseSubscriber subscriber){
        mApiService.getBanner().map(new HttpResultFunc<ArrayList<BannerBean>>()).
                compose(TransformUtils.<ArrayList<BannerBean>>defaultSchedulers())
                .subscribe(subscriber);
    }
    //热销
    public void getSaleTop8(BaseSubscriber subscriber){
        mApiService.getSaleTop8().map(new HttpResultFunc<ArrayList<HomeHotGoodsBean>>())
                .compose(TransformUtils.<ArrayList<HomeHotGoodsBean>>defaultSchedulers())
                .subscribe(subscriber);
    }

    public void getShareShopRents(BaseSubscriber subscriber,int type,String key ,int page,int pageSize){
        mApiService.getShareShopRents(type,key,page,pageSize).map(new BaseGoodsBeanFunc())
                .compose(TransformUtils.<BaseGoodsBean>defaultSchedulers())
                .subscribe(subscriber);
    }

    //搜索共享物品
    public void getSearchGoods(BaseSubscriber subscriber,int type,String searchStr,int page,int size){
        mApiService.getSearchGoods(type,searchStr,page,size).map(new BaseGoodsBeanFunc())
                .compose(TransformUtils.<BaseGoodsBean>defaultSchedulers())
                .subscribe(subscriber);
    }
    //共享物品
    public void getShareGoods(BaseSubscriber subscriber,int pageNum,int pageSize,int type){
        mApiService.getShareGoods(pageNum,pageSize,type).map(new BaseGoodsBeanFunc() )
                .compose(TransformUtils.<BaseGoodsBean>defaultSchedulers())
                .subscribe(subscriber);
    }

    //商品详情
    public void getGoodsDetails(BaseSubscriber subscriber,int id){
        mApiService.getGoodsDetails(id).map(new HttpResultFunc<GoodsDetailsBean>() )
                .compose(TransformUtils.<GoodsDetailsBean>defaultSchedulers())
                .subscribe(subscriber);
    }

    //商品分类
    public void getGoodsCate(BaseSubscriber subscriber){
        mApiService.getGoodsCate()
                .map(new HttpResultFunc<ArrayList<GoodCateBean>>())
                .compose(TransformUtils.<ArrayList<GoodCateBean>>defaultSchedulers())
                .subscribe(subscriber);
    }

    //商品列表
    public void getGoodsList(BaseSubscriber subscriber,int cateId,int page,int size){
        mApiService.getGoodsList(cateId,page,size)
                .map(new BaseGoodsBeanFunc())
                .compose(TransformUtils.<BaseGoodsBean>defaultSchedulers())
                .subscribe(subscriber);
    }


    /********************* 我的分享模块 ****************************/
    private class UserShareBeanFunc implements Func1<UserShareBean, UserShareBean> {
        @Override
        public UserShareBean call(UserShareBean httpResult) {
            if (httpResult.getCode()!=200) {
                throw new ApiException(httpResult.getMessage());
            }
            return httpResult;
        }
    }
    public void getUserShareBuy(BaseSubscriber subscriber,int pageNum,int pageSize){
        mApiService.getUserShareBuy(pageNum,pageSize).map(new UserShareBeanFunc())
                .compose(TransformUtils.<UserShareBean>defaultSchedulers())
                .subscribe(subscriber);
    }
    public void getUserShareRent(BaseSubscriber subscriber,int pageNum,int pageSize){
        mApiService.getUserShareRent(pageNum,pageSize)
                .map(new UserShareBeanFunc())
                .compose(TransformUtils.<UserShareBean>defaultSchedulers())
                .subscribe(subscriber);
    }

    public void getBuyAndRent(BaseSubscriber subscriber,int pageNum ,int pageSize,int type){
        mApiService.getBuyAndRent(pageNum,pageSize,type)
                .map(new UserShareBeanFunc())
                .compose(TransformUtils.<UserShareBean>defaultSchedulers())
                .subscribe(subscriber);
    }

    //申请退款
    public void refund(BaseSubscriber subscriber,int orderId,String numCode,String res){
        mApiService.refund(orderId,numCode,res)
                .map(new HttpResultFunc<RefundBean>())
                .compose(TransformUtils.<RefundBean>defaultSchedulers())
                .subscribe(subscriber);
    }

    public void rent(BaseSubscriber subscriber,int orderId,String numCode){
        mApiService.rent(orderId,numCode)
                .map(new HttpResultFunc<RentBean>())
                .compose(TransformUtils.<RentBean>defaultSchedulers())
                .subscribe(subscriber);
    }

    /**********************    供货人供货接口   **********************/
    public void checkDevice(BaseSubscriber subscriber,String bodyJs){
        mApiService.checkDevice(bodyJs)
                .map(new HttpResultFunc<GoodsInfoBean>())
                .compose(TransformUtils.<GoodsInfoBean>defaultSchedulers())
                .subscribe(subscriber);
    }

    public void shopInspection(BaseSubscriber subscriber,int shopId,int type,String reason){
        mApiService.shopInspection(shopId,type,reason)
                .map(new HttpResultFunc<GoodsInfoBean>())
                .compose(TransformUtils.<GoodsInfoBean>defaultSchedulers())
                .subscribe(subscriber);
    }

    public void equipmentWarranty(BaseSubscriber subscriber,String num,String reason){
        mApiService.equipmentWarranty(num,reason)
                .map(new HttpResultFunc<GoodsInfoBean>())
                .compose(TransformUtils.<GoodsInfoBean>defaultSchedulers())
                .subscribe(subscriber);
    }

    public void getDeviceShops(BaseSubscriber subscriber,int page,int size,String key,String num){
        mApiService.getDeviceShops(page,size,key,num)
                .map(new HttpResultFunc<ArrayList<DeviceGoodsBean>>())
                .compose(TransformUtils.<ArrayList<DeviceGoodsBean>>defaultSchedulers())
                .subscribe(subscriber);
    }

    public void supplyGoods(BaseSubscriber subscriber,int shopId,int  bodyJs){
        mApiService.supplyGoods(shopId,bodyJs)
                .map(new HttpResultFunc<SupplyGoodsBean>())
                .compose(TransformUtils.<SupplyGoodsBean>defaultSchedulers())
                .subscribe(subscriber);

    }

    private RequestBody getBody(String s){
        return RequestBody.create(MediaType.parse("application/json;charset=utf-8"),s);
    }

}
